import 'dart:convert';
import 'dart:io';

import 'package:collection/collection.dart';
import 'package:fk_user_agent/fk_user_agent.dart';
import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_taotaoshipin/pages/login/local_user_info.dart';
import 'package:flutter_taotaoshipin/routes/app_routes.dart';
import 'package:flutter_taotaoshipin/util/device_utils.dart';
import 'package:flutter_taotaoshipin/value/constant.dart';
import 'package:flutter_taotaoshipin/value/global_config.dart';
import 'package:flutter_taotaoshipin/value/sp_key.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:get/get.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';

class Global {
  static Future init() async {
    // 初始化 flutter
    WidgetsFlutterBinding.ensureInitialized();
    // 初始化设备信息
    await Device.initDeviceInfo();
    // 初始化 shared preferences
    await SpUtil.getInstance();
    // 初始化ua
    await FkUserAgent.init();

    // 固定竖屏
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp
    ]);

    // 垃圾代码
    handleDatabase();

    // android 状态栏为透明沉浸
    if (Platform.isAndroid) {
      SystemUiOverlayStyle style =
          const SystemUiOverlayStyle(statusBarColor: Colors.transparent);
      SystemChrome.setSystemUIOverlayStyle(style);
    }

    // 设置，hud
    EasyLoading.instance
      ..loadingStyle = EasyLoadingStyle.dark
      ..userInteractions = false
      ..dismissOnTap = false;

    // 钥匙串账号同步到本地
    await syncLocalUserInfo();
  }

  /// 打开用户协议
  static void openUserProtocol() {
    Get.toNamed(
      AppRoutes.webview,
      arguments: {
        'title': '用户协议',
        'url': GlobalConfig.useragreement,
      },
    );
  }

  /// 打开隐私政策
  static void openPravicyPolicy() {
    Get.toNamed(
      AppRoutes.webview,
      arguments: {
        'title': '隐私政策',
        'url': GlobalConfig.privacy,
      },
    );
  }

  /// 打开自动续费服务协议
  static void openVipUserProtocol() {
    Get.toNamed(
      AppRoutes.webview,
      arguments: {
        'title': '会员服务协议',
        'url': GlobalConfig.vipUseragreement,
      },
    );
  }

  /// 打开自动续费规则
  static void openAutoRenewPolicy() {
    Get.toNamed(
      AppRoutes.webview,
      arguments: {
        'title': '自动续费规则',
        'url': GlobalConfig.autoRenewPolicy,
      },
    );
  }

  /// 打开最终用户许可协议
  static void openAppleEULA() {
    Get.toNamed(
      AppRoutes.webview,
      arguments: {
        'title': '苹果最终用户许可协议',
        'url': Constant.appleEULAUrl,
      },
    );
  }

  /// 钥匙串账号同步到本地
  static Future<void> syncLocalUserInfo() async {
    var userInfo = await Global.getLocalUserInfoKeychain();
    if (userInfo.user != null && userInfo.password != null) {
      // 同步本地
      await SpUtil.putObject(SpKey.localUserInfo, userInfo);
    }
  }

  /// 设置账户信息-钥匙串
  static Future<void> setLocalUserInfoKeychain(
      LocalUserInfo2 localUserInfo) async {
    Map map = localUserInfo.toJson();
    String jsonString = jsonEncode(map);
    await const FlutterSecureStorage()
        .write(key: SpKey.localUserInfo, value: jsonString);
  }

  /// 获取账户信息-钥匙串
  static Future<LocalUserInfo2> getLocalUserInfoKeychain() async {
    String? jsonString;
    try {
      jsonString = await const FlutterSecureStorage()
          .read(key: SpKey.localUserInfo);
    } catch (e) {
      debugPrint('钥匙串读取失败$e');
    }
    if (jsonString == null) {
      return LocalUserInfo2();
    } else {
      var json = jsonDecode(jsonString);
      return LocalUserInfo2.fromJson(json as Map<String, dynamic>);
    }
  }

  static Future<void> handleDatabase() async {
    // Get a location using getDatabasesPath
    var databasesPath = await getDatabasesPath();
    String path = join(databasesPath, 'demo.db');

// Delete the database
    await deleteDatabase(path);

// open the database
    Database database = await openDatabase(path, version: 1,
        onCreate: (Database db, int version) async {
      // When creating the db, create the table
      await db.execute(
          'CREATE TABLE Test (id INTEGER PRIMARY KEY, name TEXT, value INTEGER, num REAL)');
    });

// Insert some records in a transaction
    await database.transaction((txn) async {
      int id1 = await txn.rawInsert(
          'INSERT INTO Test(name, value, num) VALUES("some name", 1234, 456.789)');
      print('inserted1: $id1');
      int id2 = await txn.rawInsert(
          'INSERT INTO Test(name, value, num) VALUES(?, ?, ?)',
          ['another name', 12345678, 3.1416]);
      print('inserted2: $id2');
    });

// Update some record
    int? count = await database.rawUpdate(
        'UPDATE Test SET name = ?, value = ? WHERE name = ?',
        ['updated name', '9876', 'some name']);
    print('updated: $count');

// Get the records
    List<Map> list = await database.rawQuery('SELECT * FROM Test');
    List<Map> expectedList = [
      {'name': 'updated name', 'id': 1, 'value': 9876, 'num': 456.789},
      {'name': 'another name', 'id': 2, 'value': 12345678, 'num': 3.1416}
    ];
    print(list);
    print(expectedList);
    assert(const DeepCollectionEquality().equals(list, expectedList));

// Count the records
    count = Sqflite.firstIntValue(
        await database.rawQuery('SELECT COUNT(*) FROM Test'));
    assert(count == 2);

// Delete a record
    count = await database
        .rawDelete('DELETE FROM Test WHERE name = ?', ['another name']);
    assert(count == 1);

// Close the database
    await database.close();
  }
}
